<template>
  <template v-if="map">
    <el-space v-if="Array.isArray(value)">
      <template v-for="(item, index) in value">
        <el-tag :key="index" v-if="map[item]">
          <span v-html="map[item]"></span>
        </el-tag>
      </template>
    </el-space>
    <span v-else v-html="map[value]"></span>
  </template>
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue'
import { filterAttr, handleObject } from '../../common/util'
import { handleApi } from '../../common/api'
import { urlCache } from '../../common/cache'
import { isString, isPlainObj } from '@/utils/index'

const PENDING = 1,
  REJECT = 2,
  RESOLVE = 3

const instance = getCurrentInstance()
const props = defineProps({
  schema: {
    type: Object,
    required: true
  }
})
const _schema = props.schema

const attrs = handleObject(filterAttr(_schema), instance)
const cache = attrs.cache || true
const value = attrs.value
console.log('value', value);
const map = ref()
if (attrs.map) {
  map.value = attrs.map
}
const api = _schema.api

let url
function requestApi() {
  if (api) {
    if (cache) {
      if (isString(api)) {
        url = api
      } else if (isPlainObj(api)) {
        url = api.url
      }
      if (url) {
        const cacheValue = urlCache[url]
        if (cacheValue) {
          if (cacheValue.result) {
            map.value = cacheValue.result
          } else {
            cacheValue.cbs = cacheValue.cbs || []
            cacheValue.cbs.push((_map) => {
              map.value = _map
            })
          }
          if (cacheValue.status === REJECT) {
            request()
          }
          return
        } else {
          urlCache[url] = {
            status: PENDING,
            result: null
          }
          map.value = urlCache[url].result
          request()
          return
        }
      }
    }
    request()
  }
}

function request() {
  handleApi(api, instance)
    .then((data) => {
      if (cache) {
        urlCache[url].status = RESOLVE
        urlCache[url].result = data
        if (urlCache[url].cbs) {
          urlCache[url].cbs.forEach((cb) => {
            cb(data)
          })
          urlCache[url].cbs = []
        }
      }
      console.log('data', data);
      map.value = data
    })
    .catch(() => {
      if (cache) {
        urlCache[url].status = REJECT
      }
    })
}

requestApi()
</script>
